package top.wsuo.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import top.wsuo.factory.ServiceFactory;
import top.wsuo.model.Blog;
import top.wsuo.model.User;


@WebServlet("/blog/edit.do")
public class BlogEditAction extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        String title = request.getParameter("title");
        String author = ((User) session.getAttribute("user")).getUsername();
        String type = request.getParameter("type");
        String decoration = request.getParameter("decoration");
        String create_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String alter_time = "";
        String text = request.getParameter("text");
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setAuthor(author);
        blog.setType(type);
        blog.setDecoration(decoration);
        blog.setCreate_time(create_time);
        blog.setAlter_time(alter_time);
        blog.setText(text);
        try {
            ServiceFactory.createBlogService().createBlog(blog);
            System.out.println("文章保存成功");
            response.sendRedirect("../home.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文章保存失败");
            response.sendRedirect("editFailed.jsp");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doGet(request, response);
    }

}
